<?php

namespace IMT\Plugins\GeneralBundle\Controller;

use Symfony\Component\Routing\Exception\MethodNotAllowedException;

use IMT\EventBundle\Models\EventInterface;

use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Response;
use IMT\EventBundle\Form\EventGeneralType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;


class DefaultController extends Controller
{
	public function indexAction()
	{
		return $this->forward('IMTPluginsGeneralBundle:Default:show', array(
        	'idEvent' => 0
    	));
	}
	
    public function showAction($idEvent)
    {
    	$emEvent = $this->container->get('imt_event.event_manager');
    	
    	if($idEvent == 0){
    		$event = $emEvent->createEvent();
    	} else {
	    	$event = $emEvent->findEventBy(array('id' => $idEvent));
	    	 
	    	if(!$event)
	    		throw $this->createNotFoundException('L\'événement recherché n\'existe pas');
    	}
    	
    	$form = $this->createForm(new EventGeneralType(), $event);
    	$user = $this->get('security.context')->getToken()->getUser();
    	$accounts = $this->getDoctrine()->getRepository('IMTAccountBundle:Account')->findByActiveAndUser(true, $user);
    	
        return $this->render('IMTPluginsGeneralBundle:Default:index.html.twig', array(
        	'form' => $form->createView(),
        	'event' => $event,
        	'accounts' => $accounts
        ));
    }
        
    public function editAJAXAction($idEvent)
    {
	    $return = array('result' => 500, 'msg' => 'Une erreur inconnue est survenue');
	    
    	try {
	    	$request = $this->getRequest();
	    	$em = $this->getDoctrine()->getEntityManager();
	    		    	 
	    	if('POST' == $request->getMethod()){
	    		
		    	$emEvent = $this->container->get('imt_event.event_manager');
		    	$validator = $this->get('validator');

		    	if($idEvent == 0){
		    		$event = $emEvent->createEvent();
		    	} else {
		    		$event = $emEvent->findEventBy(array('id' => $idEvent));
		    		 
		    		if(!$event)
		    			throw $this->createNotFoundException('L\'événement à modifier n\'existe pas');
		    	}
		    	 		    	
		    	$event = $emEvent->hydrateEvent($event, $request);
		    	$errors = $validator->validate($event);
		    	
		    	if(count($errors) > 0){
		    		$return['result'] = 400;
		    		$return['msg'] = 'Des erreurs ont été détectées'; 
		    		$return['errors'] = $errors;
    				return new Response(json_encode($return));		    		
		    	} else {
    				$emEvent->updateEvent($event);
    			
		    		$return['result'] = 200;
		    		$return['msg'] = ($idEvent == 0) ? 'L\'événement a été crée ! Actualisation ...' : 'L\'événement a été modifié !';   
		    		$return['idEvent'] = $event->getId();
		    		if($idEvent == 0) $return['refresh'] = $this->generateUrl('event_homepage', array('id' => $event->getId()));
    				return new Response(json_encode($return));
		    	}
	    	} else {
	    		throw new MethodNotAllowedException('POST');
	    	}
    	} catch(NotFoundHttpException $e){
    		return new Response(json_encode(array('result' => 500, 'msg' => $e->getMessage())));
    	} catch(AccessDeniedException $e){
    		return new Response(json_encode(array('result' => 500, 'msg' => $e->getMessage())));
    	} catch(\Exception $e){
    		return new Response(json_encode(array(
    				'result' => 500, 
    				'msg' => 'Une erreur est survenue au niveau du serveur', 
    				'debug' => $e->getMessage()
    		)));
    	}
	    	
	    return new Response(json_encode($return));
    }

}
